package com.weijianhuawen.wjblog.admin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weijianhuawen.wjblog.admin.mode.vo.role.*;
import com.weijianhuawen.wjblog.admin.service.AdminRoleService;
import com.weijianhuawen.wjblog.common.domain.dos.UserDo;
import com.weijianhuawen.wjblog.common.domain.dos.UserRoleDo;
import com.weijianhuawen.wjblog.common.domain.mapper.UserDetailMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.UserMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.UserRoleMapper;
import com.weijianhuawen.wjblog.common.enums.ResponseCodeEnum;
import com.weijianhuawen.wjblog.common.enums.UserRoleEnum;
import com.weijianhuawen.wjblog.common.exception.BizException;
import com.weijianhuawen.wjblog.common.utils.PageResponse;
import com.weijianhuawen.wjblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2025-02-05 19:46
 */

@Service
@Slf4j
public class AdminRoleServiceImpl implements AdminRoleService {
    // 注入用户账号mapper
    @Resource
    private UserMapper userMapper;
    // 注入用户角色mapper
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResponse findUserRolePageList(FindUserRolePageListReqVo vo) {
        // 获取查询条件信息
        Long current = vo.getCurrent();
        Long size = vo.getSize();
        Long userId = vo.getUserId();

        String username = vo.getUsername();

        // 进行分页查询
        Page<UserDo> page = userMapper.selectUserPageList(current, size, userId, username);
        // 获取查询数据
        List<UserDo> userDos = page.getRecords();

        List<FindUserRolePageListRspVo> vos = Lists.newArrayList();
        // 格式化数据
        if (!CollectionUtils.isEmpty(userDos)) {
            // 遍历数据
            userDos.forEach(userDo -> {
                // 获取用户名
                String name = userDo.getUsername();
                // 查询用户角色列表
                List<UserRoleDo> roleDos = userRoleMapper.selectUserRoleByUsername(name);
                if (CollectionUtils.isEmpty(roleDos)) {
                    // 用户未创建角色信息，自动创建普通用户
                    UserRoleDo userRoleDo = UserRoleDo.builder()
                            .role(UserRoleEnum.ROLE_VISITOR.getRoleType())
                            .username(name)
                            .build();
                    // 插入数据
                    userRoleMapper.insert(userRoleDo);
                    roleDos = userRoleMapper.selectUserRoleByUsername(name);
                }
                log.info(roleDos.toString());
                // 获取用户角色数据并转换
                List<Integer> roles = roleDos.stream()
                        .map(userRoleDo -> {
                            if (Objects.equals(UserRoleEnum.ROLE_ADMIN.getRoleType(), userRoleDo.getRole()))
                                return UserRoleEnum.ROLE_ADMIN.getRoleCode();
                            else if (Objects.equals(UserRoleEnum.ROLE_VISITOR.getRoleType(), userRoleDo.getRole()))
                                return UserRoleEnum.ROLE_VISITOR.getRoleCode();
                            else if (Objects.equals(UserRoleEnum.ROLE_COMMON.getRoleType(), userRoleDo.getRole()))
                                return UserRoleEnum.ROLE_COMMON.getRoleCode();
                            else return -1;
                        }).collect(Collectors.toList());
                // 构造数据
                log.info(roles.toString());
                FindUserRolePageListRspVo findUserRolePageListRspVo = FindUserRolePageListRspVo.builder()
                        .userId(String.valueOf(userDo.getId()))
                        .username(name)
                        .roles(roles)
                        .build();
                // 添加数据
                vos.add(findUserRolePageListRspVo);
            });
        }

        // 返回响应数据
        return PageResponse.success(page, vos);

    }

    @Override
    public Response addUserRole(AddUserRoleReqVo vo) {
        // 获取添加信息
        Long userId = vo.getUserId();
        String username = vo.getUsername();
        Integer roleCode = vo.getRoleCode();
        // 转换用户角色信息
        String roleType = transRoleCodeToType(roleCode);
        // 验证用户id与用户名是否统一
        UserDo userDo = userMapper.selectById(userId);
        if (Objects.isNull(userDo) || !Objects.equals(username, userDo.getUsername())) {
            throw new BizException(ResponseCodeEnum.USER_NAME_AND_ID_ERROR);
        }

        // 查询用户下的角色信息
        List<UserRoleDo> userRoleDos = userRoleMapper.selectUserRoleByUsername(username);
        // 转换
        List<String> roles = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(userRoleDos)) roles = userRoleDos.stream().map(UserRoleDo::getRole).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(roles) && roles.contains(roleType)) {
            log.warn("【角色管理服务】 目标用户添加角色已存在， 添加用户id：{}， 添加角色类型：{}", userId, roleType);
            throw new BizException(ResponseCodeEnum.USER_ROLE_ALREADY_EXIST);
        }
        // 添加用户角色
        UserRoleDo roleDo = UserRoleDo.builder()
                .username(username)
                .role(roleType)
                .build();

        userRoleMapper.insert(roleDo);
        return Response.success();
    }

    @Override
    public Response updateUserRole(UpdateUserRoleReqVo vo) {
        // 获取添加信息
        Long userId = vo.getUserId();
        String username = vo.getUsername();
        Integer roleCode = vo.getRoleCode();
        Integer newRoleCode = vo.getNewRoleCode();
        // 转换用户角色信息
        String roleType = transRoleCodeToType(roleCode);
        String newRoleType = transRoleCodeToType(newRoleCode);
        // 验证用户id与用户名是否统一
        UserDo userDo = userMapper.selectById(userId);
        if (Objects.isNull(userDo) || !Objects.equals(username, userDo.getUsername())) {
            throw new BizException(ResponseCodeEnum.USER_NAME_AND_ID_ERROR);
        }

        // 查询用户下的角色信息
        UserRoleDo userRoleDo = userRoleMapper.selectUserRoleByUsernameAndRole(username, roleType);
        UserRoleDo roleDo = userRoleMapper.selectUserRoleByUsernameAndRole(username, newRoleType);
        if (Objects.isNull(userRoleDo)) {
            log.warn("【角色管理服务】 目标用户修改角色不存在， 修改用户id：{}， 修改角色类型：{}，原角色类型：{}", userId, newRoleType, roleType);
            throw new BizException(ResponseCodeEnum.USER_ROLE_NOT_EXIST);
        }
        if (Objects.nonNull(roleDo)) {
            log.warn("【角色管理服务】 目标用户修改角色已存在， 修改用户id：{}， 修改角色类型：{}", userId, newRoleType);
            throw new BizException(ResponseCodeEnum.USER_ROLE_ALREADY_EXIST);
        }

        // 修改用户角色
        userRoleDo.setRole(newRoleType);
        userRoleMapper.updateById(userRoleDo);
        return Response.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response deleteUserRole(DeleteUserRoleReqVo vo) {
        // 获取信息
        Long userId = vo.getUserId();
        String username = vo.getUsername();
        Integer roleCode = vo.getRoleCode();
        String roleType = transRoleCodeToType(roleCode);

        // 验证用户id与用户名是否统一
        UserDo userDo = userMapper.selectById(userId);
        if (Objects.isNull(userDo) || !Objects.equals(username, userDo.getUsername())) {
            throw new BizException(ResponseCodeEnum.USER_NAME_AND_ID_ERROR);
        }

        // 查询用户下的角色信息
        UserRoleDo userRoleDo = userRoleMapper.selectUserRoleByUsernameAndRole(username, roleType);
        if (Objects.isNull(userRoleDo)) {
            log.warn("【角色管理服务】 目标用户删除角色不存在， 删除角色用户id：{}， 删除角色类型：{} ", userId, roleType);
            throw new BizException(ResponseCodeEnum.USER_ROLE_NOT_EXIST);
        }

        // 查询用户下的角色信息
        List<UserRoleDo> userRoleDos = userRoleMapper.selectUserRoleByUsername(username);
        if (Objects.isNull(userRoleDos) || userRoleDos.size() <= 1) {
            log.warn("【角色管理服务】 目标用户删除角色至少保留一个，当前角色数量小于或等于1，无法删除， 删除角色用户id：{}， 删除角色类型：{} ", userId, roleType);
            throw new BizException(ResponseCodeEnum.USER_ROLE_NUMBER_LIMIT);
        }

        // 删除角色
        Long id = userRoleDo.getId();
        userRoleMapper.deleteById(id);

        return Response.success();
    }

    // 将用户角色code转换为type
    private String transRoleCodeToType(Integer roleCode) {
        return Objects.equals(UserRoleEnum.ROLE_VISITOR.getRoleCode(), roleCode)
                ? UserRoleEnum.ROLE_VISITOR.getRoleType() : Objects.equals(UserRoleEnum.ROLE_ADMIN.getRoleCode(), roleCode)
                ? UserRoleEnum.ROLE_ADMIN.getRoleType() : Objects.equals(UserRoleEnum.ROLE_COMMON.getRoleCode(), roleCode)
                ? UserRoleEnum.ROLE_COMMON.getRoleType() : UserRoleEnum.ROLE_OTHER.getRoleType();
    }
}
